function createSilentWavFile(durationInSeconds: number) {
  const sampleRate = 44100; // CD quality audio
  const bitsPerSample = 8; // 8-bit unsigned integers for minimal quality
  const channelCount = 1; // Mono
  const byteRate = (sampleRate * bitsPerSample * channelCount) / 8;
  const sampleCount = durationInSeconds * sampleRate;
  const fileSize = 44 + sampleCount; // WAV header size is 44 bytes

  // Create an ArrayBuffer with the correct size
  const buffer = new ArrayBuffer(fileSize);
  const view = new DataView(buffer);

  // RIFF Chunk
  setViewString(view, 0, 'RIFF', 4); // RIFF ID
  view.setUint32(4, fileSize - 8, true); // RIFF Size
  setViewString(view, 8, 'WAVE', 4); // WAVE

  // fmt Subchunk
  setViewString(view, 12, 'fmt ', 4); // fmt ID
  view.setUint32(16, 16, true); // fmt Size
  view.setUint16(20, 1, true); // PCM Format
  view.setUint16(22, channelCount, true); // Channels
  view.setUint32(24, sampleRate, true); // Sample Rate
  view.setUint32(28, byteRate, true); // Byte Rate
  view.setUint16(32, (bitsPerSample * channelCount) / 8, true); // Block Align
  view.setUint16(34, bitsPerSample, true); // Bits per Sample

  // data Subchunk
  setViewString(view, 36, 'data', 4); // data ID
  view.setUint32(40, sampleCount, true); // data Size

  // Fill the data subchunk with zeros (silence)
  for (let i = 44; i < fileSize; i++) {
    view.setUint8(i, 0);
  }

  return new Blob([view.buffer], { type: 'audio/wav' });
}

// Helper function to set strings into the DataView as ASCII
function setViewString(view: DataView, offset: number, str: string, length: number) {
  for (let i = 0; i < length; i++) {
    view.setUint8(offset + i, str.charCodeAt(i));
  }
}

// Generate a URL for the silent WAV file
function generateSilentAudioUrl(duration: number) {
  const blob = createSilentWavFile(Math.ceil(duration));
  return URL.createObjectURL(blob);
}

self.addEventListener('message', async ({ data }) => {
  const { duration } = data;

  const url = generateSilentAudioUrl(duration);
  self.postMessage(url);
});
